package edu.hnu.cloudflight.android.server;

import java.util.ArrayList;
import java.util.List;

import edu.hnu.cloudflight.android.MyApplication;
import edu.hnu.cloudflight.android.domain.Flight;
import edu.hnu.cloudflight.android.util.DateUtil;
import edu.hnu.cloudflight.android.util.FlightDBHelper;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

public class FlightDBServer {
	
	private static FlightDBServer instant;
	
	private FlightDBHelper flightDBHelp;
	
	public static FlightDBServer getInstant(Context context){
		if(instant==null){
			instant = new FlightDBServer(context);
		}
		return instant;
	}
	
	
	private FlightDBServer(Context context){
		flightDBHelp = new FlightDBHelper(context);
	}
	
	
	public boolean addFlightCollect(Flight flight){
		SQLiteDatabase database = flightDBHelp.getWritableDatabase();
		String date = DateUtil.getNowDateToString();
		String sql ="insert into flight (flightnum,start,end,company,date,user) values(?,?,?,?,?,?)";
		database.execSQL(sql, new Object[]{flight.name,flight.start,flight.end,flight.complany,date,MyApplication.appToken});
		database.close();
		return true;
	}
	
	public boolean delFlightCollect(String flightNum){
		SQLiteDatabase database = flightDBHelp.getWritableDatabase();
		String sql ="delete from flight where flightnum = ? and user =?";
		database.execSQL(sql, new Object[]{flightNum,MyApplication.appToken});
		return true;
	}


	public List<Flight> getAllFlights() {
		List<Flight> list = new ArrayList<Flight>();
		SQLiteDatabase database = flightDBHelp.getReadableDatabase();
		String sql = "select flightnum,start,end,company,date from flight where user =? ";
		Cursor cursor = database.rawQuery(sql, new String[]{MyApplication.appToken});
		while(cursor.moveToNext()){
			Flight temp = new Flight();
			temp.name=cursor.getString(cursor.getColumnIndex("flightnum"));
			temp.start=cursor.getString(cursor.getColumnIndex("start"));
			temp.end=cursor.getString(cursor.getColumnIndex("end"));
			temp.complany=cursor.getString(cursor.getColumnIndex("company"));
			list.add(temp);
		}
		database.close();
		return list;
	}

}
